package 实验五;


import test1.Convert;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

/**
 * Created by besti on 2018/6/9.
 */
public class SocketClient1 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        //1.建立客户端Socket连接，指定服务器位置和端口
//        Socket socket = new Socket("localhost",8080);
        Socket socket = new Socket("127.0.0.1",8800);

        //2.得到socket读写流
        OutputStream outputStream = socket.getOutputStream();
        //       PrintWriter printWriter = new PrintWriter(outputStream);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        //输入流
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        //3.利用流按照一定的操作，对socket进行读写操作
        System.out.println("请输入一个想计算的中缀表达式：");
        Scanner scan =new Scanner(System.in);
        String info1 =scan.nextLine();
        //String info1 = " 用户名：Tom，密码：123456";
        Convert suffix = new Convert();
        String info2 = suffix.transit(info1);
        System.out.println(info2);
        FileInputStream f=new FileInputStream("key1.dat");
        ObjectInputStream b=new ObjectInputStream(f);
        Key k=(Key)b.readObject( );
        Cipher cp=Cipher.getInstance("DESede");
        cp.init(Cipher.ENCRYPT_MODE, k);
        byte ptext[]=info2.getBytes("UTF8");
        for(int i=0;i<ptext.length;i++){
            System.out.print(ptext[i]+",");
        }
        System.out.println("");
        byte ctext[]=cp.doFinal(ptext);//进行加密。
        String aa="";
        for(int i=0;i<ctext.length;i++){
            aa+=ctext[i] +",";
        }
        String info3=aa;

        String info = new String(info3.getBytes("GBK"),"utf-8");

        outputStreamWriter.write(info);
        outputStreamWriter.flush();
        socket.shutdownOutput();
        //接收服务器的响应
        String reply = null;
        while (!((reply = bufferedReader.readLine()) ==null)){
            System.out.println("计算后缀表达式结果为：" + reply);
        }
        //4.关闭资源
        bufferedReader.close();
        inputStream.close();
        outputStreamWriter.close();
        //printWriter.close();
        outputStream.close();
        socket.close();
    }
}
